<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container{
            width: 600px;
            height: 600px;
            border: 1px solid;
            position: relative;
        }
        .box{
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            left: 0px;
            top:0px
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box"></div>
    </div>
    <div class="score">分数:0</div>
<script>
 var boxEle = document.querySelector(".box");
 var dir = "left";
 var speed = 4;
 document.onkeydown = function(e){
    var key = e.key;
    if(key=="ArrowRight"){
        dir = "left"
        speed = Math.abs(speed);
    }else if(key=="ArrowDown"){
        dir = "top";
        speed = Math.abs(speed);
    }else if(key=='ArrowLeft'){
        dir = "left"
        speed = -Math.abs(speed);
    }else if(key=="ArrowUp"){
        dir = "top";
        speed = -Math.abs(speed);
    }
 }

//  来一个绿色食物 ，红色碰到绿色之后 绿色食物消失
var food =  createFood()
var num = 0;
setInterval(function(){
    var leftNum = parseInt( getComputedStyle(boxEle)[dir]);
    boxEle.style[dir] = leftNum + speed + "px";

    // 检测碰撞 
    // A 是 food 元素
    var AminX = food.offsetLeft;
    var AmaxX = AminX + food.offsetWidth;
    var AminY = food.offsetTop;
    var AmaxY = AminY+food.offsetHeight;

    // B 是 红色的方块  boxEle
    var BminX = boxEle.offsetLeft;
    var BmaxX=  BminX + boxEle.offsetWidth;
    var BminY = boxEle.offsetTop;
    var BmaxY = BminY + boxEle.offsetHeight;

    if(AmaxX>BminX && AminX<BmaxX && AmaxY>BminY && AminY<BmaxY){
        // console.log("碰了");
        food.remove();
        food = createFood();
        num++;
        document.querySelector(".score").innerHTML = "分数："+num;
    }





}, 50);

// arrowfunction：箭头函数 ；
function createFood(){
    var containerEle = document.querySelector(".container");
    var food = document.createElement("div");
    food.style.width = "50px"
    food.style.height = "50px"
    food.style.background = "blue";
    food.style.left = randomNum(0,containerEle.clientWidth-50) + "px";
    food.style.top = randomNum(0,containerEle.clientHeight-50) + "px";
    food.style.position = "absolute";
    containerEle.appendChild(food);
    return food;
}




function randomNum(min,max){
    return parseInt(Math.random()*(max-min+1))+min;
}




</script>
</body>
</html>